package com.zhtools.utils;

/**
 * 文本工具类
 */
public final class TextUtil {
    /**
     * 根据传入的长度截取字符串
     *
     * @param src  String
     * @param len  int
     * @param plac String 如果字符串超过，将以该字符串作为后缀
     * @return String
     */
    public static String cutString(String src, int len, String plac) {
        if (src == null) {
            return "";
        }
        if (plac == null || "".equals(plac.trim())) {
            plac = "";
        }

        try {
            if (src.getBytes("gbk").length <= len) {
                return src;
            }
            byte[] bytes = src.getBytes("gbk");
            int idx = len - plac.getBytes("gbk").length;
            if (idx < 0) {
                return "";
            }
            String result = new String(bytes, 0, idx, "gbk");
            String test = src.substring(0, result.length());
            if (test.equals(result)) {
                return result + plac;
            }
            idx--;
            result = new String(bytes, 0, idx, "gbk");
            return result + plac;

        } catch (Exception e) {
            e.printStackTrace();
            return src;
        }
    }
}
